<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use App\Common\Constants\ErrorCode;
use App\Exception\BusinessException;
use Mine\MineModel;

/**
 * @property int $id 主键
 * @property int $main_uid 主账号id
 * @property int $uid 私域用户ID
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property string $end_at 截止时间
 * @property int $forever 1-长期
 * @property string $link 跳转链接
 * @property int $status 1-已发布  2已截止 3未发布
 * @property string $title 标题
 * @property string $describe 问卷说明
 * @property string $image 图片
 * @property int $submit_total 提交人数
 * @property int $click_total 点击人数
 * @property int $write_total 填写人数
 * @property int $corp_id 企业id
 */
class ChSmartQuestionnaire extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_smart_questionnaire';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'main_uid', 'uid', 'created_at', 'updated_at', 'end_at', 'forever', 'link', 'status', 'title', 'describe', 'image', 'submit_total', 'click_total', 'write_total', 'corp_id'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'main_uid' => 'integer', 'uid' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'forever' => 'integer', 'status' => 'integer', 'submit_total' => 'integer', 'click_total' => 'integer', 'write_total' => 'integer', 'corp_id' => 'integer'];

    public function user()
    {
        return $this -> hasOne(ChUser::class,'id','uid');
    }

    public static function saveQuestionnaire($uid,$mainUid,$corpId,$data = [],$id = 0)
    {
        $model = new self();
        if($id){
            $model = self::where('id',$id) -> first();
            if(empty($model)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }
        $model -> uid = $uid;
        $model -> main_uid = $mainUid;
        $model -> corp_id = $corpId;
        $model -> title = $data[0]['content']['title'];
        $model -> image = $data[0]['content']['image'];
        $model -> describe = $data[0]['content']['describe'];
        $model -> save();
        ChSmartQuestionnaireItem::saveItems($model -> id,$data);
        return $model;
    }

    public function items()
    {
        return $this -> hasMany(ChSmartQuestionnaireItem::class,'questionnaire_id','id');
    }
}
